package cn.com.easy.utils;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.io.FileUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

/**
 * 把PDF转成图片的工具类
 * 
 * @author nibili 2017年6月8日
 * 
 */
public class IcePdfUtils {

	public static void main(String[] args) throws Exception {
		int index = IcePdfUtils.pdfToImgae("C:/Users/Administrator/Desktop/6月月刊.pdf", "C:/Users/Administrator/Desktop/6月", 2);
		System.out.println(index);

		System.out.println("Hit Enter in console to stop server");
		if (System.in.read() != 0) {
			System.out.println("Server stopped");
		}
	}

	/**
	 * pdf转图片，会按页转存图片
	 * 
	 * @param pdfFilePath
	 * @param ouputFolderPath
	 * @throws IOException
	 * @author nibili 2017年6月8日
	 */
	public static int pdfToImgae(String pdfFilePath, String ouputFolderPath) throws IOException {
		// select the path here
		// you can use the direct filepath or absolute path
		// you can change it as you like
		// String filePath = "C:/Users/Administrator/Desktop/内刊/内刊.pdf";
		Document document = new Document();
		document.setFile(pdfFilePath);
		// determine the scale of the image
		// and the direction of the image
		float scale = 1.3f;
		float rotation = 0f;
		int totalPages = document.getNumberOfPages();
		for (int i = 0; i < totalPages; i++) {
			BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
			RenderedImage rendImage = image;
			// System.out.println("/t capturing page " + i);——only for
			// testing,you can delete it
			// the next two lines determine the saving path
			// you can change it via the way you like
			File file = new File(ouputFolderPath + "/img_" + (i + 1) + ".png");
			ImageIO.write(rendImage, "png", file);
			image.flush();
		}
		document.dispose();
		return totalPages;
	}

	/**
	 * pdf转图片，会按页转存图片
	 * 
	 * @param pdfFilePath
	 * @param ouputFolderPath
	 * @param verticleCount
	 *            每天一页水平等分切割数量
	 * @return
	 * @throws IOException
	 * @author nibili 2017年7月7日
	 */
	public static int pdfToImgae(String pdfFilePath, String ouputFolderPath, int verticleCount) throws IOException {
		if (verticleCount <= 0) {
			// 最少要分割保存成一份 如果一份，直接按单张图来处理
			return pdfToImgae(pdfFilePath, ouputFolderPath);
		}
		// select the path here
		// you can use the direct filepath or absolute path
		// you can change it as you like
		// String filePath = "C:/Users/Administrator/Desktop/内刊/内刊.pdf";
		Document document = new Document();
		document.setFile(pdfFilePath);
		// determine the scale of the image
		// and the direction of the image
		float scale = 1.3f;
		float rotation = 0f;
		int totalPages = document.getNumberOfPages();
		// 图片文件序号
		int fileIndex = 0;
		for (int i = 0; i < totalPages; i++) {
			BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
			RenderedImage rendImage = image;
			String filePath = ouputFolderPath + "/img_original_" + (i + 1) + ".png";
			// 先写入单页图片
			File file = new File(filePath);
			ImageIO.write(rendImage, "png", file);
			image.flush();
			// 切割图片
			// 每张图片的宽度 和 高度，按均等分计算
			int width = rendImage.getWidth() / verticleCount;
			int height = rendImage.getHeight();
			for (int k = 0; k < verticleCount; k++) {
				cutImage(filePath, ouputFolderPath, ++fileIndex, k * width, 0, width, height);
			}
			// 删除原文件
			file = new File(filePath);
			FileUtils.forceDelete(file);
		}
		document.dispose();
		return fileIndex;
	}

	/**
	 * 图片裁剪通用接口
	 * 
	 * @param src
	 * @param folder
	 * @param file_index
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @throws IOException
	 * @author nibili 2017年7月7日
	 */
	private static void cutImage(String src, String folder, int file_index, int x, int y, int w, int h) throws IOException {
		@SuppressWarnings("rawtypes")
		Iterator iterator = ImageIO.getImageReadersByFormatName("png");
		ImageReader reader = (ImageReader) iterator.next();
		InputStream in = new FileInputStream(src);
		ImageInputStream iis = ImageIO.createImageInputStream(in);
		reader.setInput(iis, true);
		ImageReadParam param = reader.getDefaultReadParam();
		Rectangle rect = new Rectangle(x, y, w, h);
		param.setSourceRegion(rect);
		BufferedImage bi = reader.read(0, param);
		ImageIO.write(bi, "png", new File(folder + "/img_" + file_index + ".png"));
		in.close();
		iis.close();
	}
}
